module.exports = {
	/**
	 * @type {String} 设备id
	 */
	blueDeviceId: '',

	/**
	 * @type {String} 设备读取特征UUID
	 */
	characteristicUUId_read: '',
	characteristicUUId_read_temp: '',

	/**
	 * @type {String} 通信设备名称
	 */
	deviceName: 'MyScale',

	/**
	 * @type {String} 通信设备服务UUID
	 */
	deviceUUId: '0000FFE0-0000-1000-8000-00805F9B34FB',

	/**
	 * @type {String} 设备通知特征UUID
	 */
	characteristicUUId_notify: '',
	characteristicUUId_notify_temp: '0000FFE1-0000-1000-8000-00805F9B34FB', 

	/**
	 * @type {String} 广播事件
	 */
	hub: Vue.prototype.$eventHub || new Vue(),


	/**
	 * 1初始化蓝牙
	 */
	init() {
		/* const hexValue = "550e030d01010c060072004c468d"
		console.log('16进制内容：' + hexValue)
		let sys = parseInt(hexValue.slice(18, 20), 16);
		let dia = parseInt(hexValue.slice(22, 24), 16);
		let pul = parseInt(hexValue.slice(24, 26), 16);
		console.log("高压值 SYS：" + sys);
		console.log("低压值 DIA：" + dia);
		console.log("脉搏值 PUL：" + pul); 

		return*/
		let that = this;
		uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
			success: function(res) {
				console.log('初始化蓝牙成功=' + JSON.stringify(res))
				that.findDevices()
			},
			fail: function(err) { //如果手机上的蓝牙没有打开，可以提醒用户
				console.log('初始化蓝牙失败=' + JSON.stringify(err))
				uni.$showMsg('【蓝牙】未打开', 1000)
				/* setTimeout(function() {
					uni.navigateBack()
				}, 1000) */
			}
		})
		/* setTimeout(function() {
			test1()
		}, 3000) */
	},
	/**
	 * 2搜索设备
	 */
	findDevices() {
		let that = this
		uni.startBluetoothDevicesDiscovery({
			success: function(res) {
				console.log('开始搜索=' + JSON.stringify(res))
				//监听寻找到新设备的事件
				uni.onBluetoothDeviceFound(function(dev) {

					let devInfo = dev.devices[0];
					if (devInfo.name != '') {
						if(that.deviceName != ''){
							console.log('查找设备....,devInfo=' + JSON.stringify(devInfo))
							//找到需要的设备
							if (devInfo.name.trim() == that.deviceName) {
								// 停止搜索
								that.stopDiscovery()

								that.blueDeviceId = devInfo.deviceId
								that.connectDevices()
							}
						}
					}
				})
			},
			fail: function(err) {
				console.log('搜索失败', JSON.stringify(err))
			}
		})
	},
	/**
	 * 3连接设备
	 */
	connectDevices() {
		let that = this;
		console.log(`开始连接蓝牙设备`)
		uni.createBLEConnection({
			deviceId: that.blueDeviceId,
			success(res) {
				console.log('连接成功=' + JSON.stringify(res))
				setTimeout(function() {
					that.getService()
				}, 5000)

			},
			fail(err) {
				console.log('连接失败=' + JSON.stringify(err))
			}
		})
	},
	/**
	 * 4停止搜索
	 */
	stopDiscovery() {
		let that = this
		uni.stopBluetoothDevicesDiscovery({
			success(resStop) {
				console.log('停止成功=' + JSON.stringify(resStop))
			},
			fail(err) {
				console.log('停止失败=' + JSON.stringify(err))
			}
		})
	},
	/**
	 * 5获取服务
	 */
	getService() {
		let that = this
		//获取serviceid
		uni.getBLEDeviceServices({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立连接
			deviceId: that.blueDeviceId,
			success(res) {
				console.log('设备服务获取成功=' + JSON.stringify(res))
				for (let i = 0; i < res.services.length; i++) {
					if (res.services[i].uuid == that.deviceUUId) {
						//console.log('设备服务获取成功=' + JSON.stringify(res))
						that.getCharacteristics()
					}
				}
			},
			fail(error) {
				console.log('设备服务获取失败=', JSON.stringify(error))
			}
		})
	},
	/**
	 * 6获取特征
	 */
	getCharacteristics() {
		let that = this
		uni.getBLEDeviceCharacteristics({
			deviceId: that.blueDeviceId, // 设备ID，在【4】里获取到
			serviceId: that.deviceUUId, // 服务UUID，在【6】里能获取到
			success(res) {
				const characteristics = res.characteristics
				console.log("获取特征=" + JSON.stringify(characteristics))
				for (let i = 0; i < characteristics.length; i++) {
					if (characteristics[i].properties.read && that.characteristicUUId_read_temp ==
						characteristics[i].uuid) {
						that.characteristicUUId_read = characteristics[i].uuid
					}
					if (characteristics[i].properties.notify && that.characteristicUUId_notify_temp ==
						characteristics[i].uuid) {
						that.characteristicUUId_notify = characteristics[i].uuid
					}
				}
				if (that.characteristicUUId_notify == '') {
					console.log('获取notify——uuid失败')
				}
				console.log('特征数据获取完成')
				that.acceptNotify()
			},
			fail(err) {
				console.log("获取特征失败=" + JSON.stringify(err))
			}
		})
	},
	/**
	 * 关闭连接
	 */
	closeBleConn() {
		let that = this
		uni.closeBLEConnection({
			deviceId: that.blueDeviceId,
			success(res) {
				console.log('关闭连接=' + JSON.stringify(res))
			}
		})
	},
	/**
	 * 关闭蓝牙
	 */
	closeBlue() {
		uni.closeBluetoothAdapter({
			success(res) {
				console.log('关闭蓝牙=' + JSON.stringify(res))
			}
		})
	},
	/**
	 * 写入数据
	 */
	sendData() {
		let that = this
		const content = "147"
		let data_01 = that.charToHex(content)
		//0x930x8e0x050x000x080x0D0x000x1A    关闭语音
		//0x930x8e0x050x000x080x0B0x000x18    自动测试
		//0x930x8e0x050x000x080x130x000x1A    测试项数
		//0x930x8E0x080x000x080x010x430x4F0x4E0x540x45     设备确认
		const data_02 = "0x930x8e0x050x000x080x0B0x000x18"
		let data_02Array = that.hexstrToArrayBuffer(data_02)

		console.log('发送data=' + data_01)
		let buff = Buffer.from(data_01) //字符串转buff
		//console.log('buff=' + buff)
		uni.writeBLECharacteristicValue({
			// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
			deviceId: that.blueDeviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",
			// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
			characteristicId: "0000ffe1-0000-1000-8000-00805f9b34fb", //第二步写入的特征值
			// 这里的value是ArrayBuffer类型
			value: data_02Array,
			writeType: 'writeNoResponse',
			success: function(res) {
				//此时设备已接收到你写入的数据
				console.log("设备信息写入成功=" + JSON.stringify(res))
			},
			fail: function(err) {
				console.log(`数据写入失败=${JSON.stringify(err)}`)
			}
		})
	},
	//读取
	readDevices() {
		let that = this;
		uni.readBLECharacteristicValue({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: that.blueDeviceId,
			// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",
			// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			characteristicId: "0000ffe1-0000-1000-8000-00805f9b34fb",
			success(res) {
				console.log('读取数据成功:', res)
			},
			fail(err) {
				console.log('读取数据失败:', err)
			}
		})
	},
	/**
	 * 开启消息监听
	 */
	acceptNotify() {
		let that = this;
		console.log(
			`deviceId=${that.blueDeviceId},serviceId=${that.deviceUUId},characteristicId=${that.characteristicUUId_notify}`
		)
		uni.notifyBLECharacteristicValueChange({
			state: true, // 启用 notify 功能
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立连接
			deviceId: that.blueDeviceId,
			// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			serviceId: that.deviceUUId,
			// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			characteristicId: that.characteristicUUId_notify,
			success(res) {
				console.log(`notify监听成功=${JSON.stringify(res)},等待返回`)
				setTimeout(function() {
					that.sendData();
				}, 2000)
				// 必须在这里的回调才能获取
				uni.onBLECharacteristicValueChange(function(res) {
					let getV = res.value
					console.log(`通知notify=${getV}`)
					//console.log(`通知notify内容长度=${getV.byteLength}`)
					//dataview
					//let dataView = new DataView(getV);
					//console.log(dataView.getInt32(0))


					//获取16进制内容
					const hexValue = that.buf2hex(getV)
					console.log('16进制内容：' + hexValue)
					that.decodeData(hexValue)

					//console.log('over')
				})
			},
			fail(err) {
				console.log(`notify监听失败=${JSON.stringify(err)}`)
			},
		})
	},
	decodeData(value) {
		let weight = parseInt(value.substring(4, 8), 16) / 100
		let height = parseInt(value.substring(30, 34), 16) / 10
		let imp0 = value.substring(28, 30) + value.substring(34, 36)
		
		let result = height / 100
		result = result * result
		result = weight / result
		result = result.toFixed(2)
		
		console.log("您的身高是：" + height + 'cm')
		console.log("您的体重是：" + weight + 'kg')
		console.log("BMI：" + result)
		
		console.log("阻抗：" + parseInt(imp0, 16))
		console.log("测量结束")
	},
	uint8ArrayToString(u8a) {
		var dataStr = "";
		for (var i = 0; i < u8a.length; i++) {
			dataStr += String.fromCharCode(u8a[i])
		}
		return dataStr;
	},
	arrayBufferToString(arr) {
		if (typeof arr === 'string') {
			return arr;
		}
		var dataview = new DataView(arr.data);
		var ints = new Uint8Array(arr.data.byteLength);
		for (var i = 0; i < ints.length; i++) {
			ints[i] = dataview.getUint8(i);
		}
		arr = ints;
		var str = '',
			_arr = arr;
		for (var i = 0; i < _arr.length; i++) {
			var one = _arr[i].toString(2),
				v = one.match(/^1+?(?=0)/);
			if (v && one.length == 8) {
				var bytesLength = v[0].length;
				var store = _arr[i].toString(2).slice(7 - bytesLength);
				for (var st = 1; st < bytesLength; st++) {
					store += _arr[st + i].toString(2).slice(2);
				}
				str += String.fromCharCode(parseInt(store, 2));
				i += bytesLength - 1;
			} else {
				str += String.fromCharCode(_arr[i]);
			}
		}
		return str;
	},
	hexToStr(hex) {
		// 去掉字符串首尾空格
		let trimedStr = hex.trim()
		// 判断trimedStr前两个字符是否为0x，如果是则截取从第三个字符及后面所有，否则返回全部字符
		let rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr
		// 得到rawStr的长度
		let len = rawStr.length
		// 如果长度不能被2整除，那么传入的十六进制值有误，返回空字符
		if (len % 2 !== 0) {
			return ""
		}
		let curCharCode // 接收每次循环得到的字符
		let resultStr = [] // 存转换后的十进制值数组
		for (let i = 0; i < len; i = i + 2) {
			curCharCode = parseInt(rawStr.substr(i, 2), 16)
			resultStr.push(curCharCode)
		}
		// encoding为空时默认为utf-8
		let bytesView = new Uint8Array(resultStr) // 8 位无符号整数值的类型化数组
		// TextEncoder和TextDecoder对字符串和字节流互转  
		// let str = new TextDecoder(encoding).decode(bytesView)因为小程序中没有TextDecoder,经查阅资料，下载https://github.com/inexorabletash/text-encoding并const encoding = require("./text-encoding-master/lib/encoding.js")引入后使用下面方式即可：
		let str = new encoding.TextDecoder("gbk").decode(bytesView)
		return str
	},
	buf2hex(arrayBuffer) {
		return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2)).join(
			'');
	},
	hexstrToArrayBuffer(hexStr) {
		let data_02Array = new Uint8Array(hexStr.match(/[\da-f]{2}/gi).map(function(h) {
			return parseInt(h, 16)
		}))
		return data_02Array
	},
	/**
	 * 字符串转hex
	 */
	charToHex(str) {
		if (typeof(str) == 'undefined') return null
		var hex = str.split('').map(function(char) {
			var code = char.charCodeAt(0);
			return '0x' + code.toString(16).toUpperCase() + '';
		}).join('');
		return hex;
	},
}